import React, { useEffect, useState } from 'react';

import styles from './style/index.module.less';
import {
  Button,
  Grid,
  Input,
  Link,
  Message,
  Space,
  Upload,
} from '@arco-design/web-react';
import DictionarySelect from '@/pages/system/course/dictionaryModal';
import {
  editKnowledgeApi,
  editSectionApi,
  getKnowledgeByIdApi,
  getSectionAllApi,
  getSectionByIdApi,
} from '@/request/api';
const Row = Grid.Row;
const Col = Grid.Col;

const AboutLesson = ({ node, info }) => {
  const [sectionDetail, setSectionDetail] = useState();

  const token = localStorage.getItem('userToken');
  const [introduce, setIntroduce] = useState('');
  const [fileList, setFileList] = useState([]);
  const [defaultDependsOnList, setDefaultDependsOnList] = useState([]);
  const [defaultApplyToList, setDefaultApplyToList] = useState([]);
  const [defaultRefPageList, setDefaultRefPageList] = useState([]);
  const [dependsOnList, setDependsOnList] = useState([]);
  const [applyToList, setApplyToList] = useState([]);
  const [refPageList, setRefPageList] = useState([]);

  const fetchSection = (id) => {
    getSectionByIdApi({ id })
      .then((res) => {
        const { data } = res;
        console.log(data, 'fetchSection');
        setIntroduce(data.introduce);
        const realFileList = data.refFileList.map((item) => {
          return {
            uid: item.fileKey,
            name: item.fileName,
            response: {
              data: item,
            },
          };
        });
        setFileList(realFileList);
        setDefaultDependsOnList(getSelectedValue(data.dependsOnList));
        setDefaultApplyToList(getSelectedValue(data.applyToList));
        setDefaultRefPageList(getSelectedValue(data.refPageList));
        setSectionDetail(data);
      })
      .catch((e) => {
        console.log(e);
      });
  };

  const fetchKnowledge = (id) => {
    getKnowledgeByIdApi({ id })
      .then((res) => {
        const { data } = res;
        console.log(data, 'fetchKnowledge');
        setIntroduce(data.introduce);
        const realFileList = data.refFileList.map((item) => {
          return {
            uid: item.fileKey,
            name: item.fileName,
            response: {
              data: item,
            },
          };
        });
        setFileList(realFileList);
        setDefaultDependsOnList(getSelectedValue(data.dependsOnList));
        setDefaultApplyToList(getSelectedValue(data.applyToList));
        setDefaultRefPageList(getSelectedValue(data.refPageList));
        setSectionDetail(data);
      })
      .catch((e) => {
        console.log(e);
      });
  };

  const getSelectedValue = (value) => {
    const ids = value.map((item) => {
      return [`${item.type}`, `${item.bizId}`];
    });
    console.log(ids);
    return ids;
  };

  useEffect(() => {
    if (node.id) {
      if (node.type == 0 || node.type == 1) {
        fetchKnowledge(node.id);
        console.log(node);
      } else {
        fetchSection(node.id);
      }
    }
  }, [node]);

  const save = () => {
    if (!node.id) {
      Message.warning('请选择章节或知识点');
      return;
    }
    const refFileList = fileList.map((item) => {
      return item.response.data;
    });

    const body = {
      id: node.id,
      introduce,
      refFileList,
      dependsOnList,
      applyToList,
      refPageList,
    };
    console.log(node, body);

    if (node.type == 0 || node.type == 1) {
      console.log('知识点');
      editKnowledgeApi(body)
        .then((res) => {
          const { msg } = res;
          Message.success(msg);
        })
        .catch((e) => {
          console.log(e);
        });
    } else {
      console.log('章节');
      editSectionApi(body)
        .then((res) => {
          const { msg } = res;
          Message.success(msg);
        })
        .catch((e) => {
          console.log(e);
        });
    }
  };

  return (
    <div className={styles.table}>
      <h2>{node.name || ''}</h2>
      <Row>
        <Col span={4} offset={2} className={[styles.input, styles.col]}>
          基础介绍
        </Col>
        <Col span={16} className={styles.input}>
          <Input
            style={{ width: '100%', height: '100%' }}
            allowClear
            placeholder="请输入内容"
            value={introduce}
            onChange={(value) => setIntroduce(value)}
          />
        </Col>
      </Row>

      <Row>
        <Col span={4} offset={2} className={[styles.item, styles.col]}>
          参考资料
        </Col>
        <Col span={16} className={styles.item}>
          {/*<Link>+添加文件</Link>*/}
          <Upload
            headers={{ Authorization: token }}
            showUploadList={{
              startIcon: (
                <Button size="mini" type="text">
                  开始上传
                </Button>
              ),
              cancelIcon: (
                <Button size="mini" type="text">
                  取消上传
                </Button>
              ),
              reuploadIcon: (
                <Button size="mini" type="text">
                  点击重试
                </Button>
              ),
            }}
            progressProps={{
              size: 'small',
              type: 'line',
              showText: true,
              width: '100%',
            }}
            multiple
            fileList={fileList}
            action={`${process.env.REACT_APP_BASE_URL}fileStore/upload`}
            onChange={setFileList}
            onProgress={(file) => {
              setFileList((v) => {
                return v.map((x) => {
                  return x.uid === file.uid ? file : x;
                });
              });
            }}
          >
            <Link>+上传文件</Link>
          </Upload>
        </Col>
      </Row>

      <Row>
        <Col span={4} offset={2} className={[styles.item, styles.col]}>
          依赖于
        </Col>
        <Col span={16} className={styles.item}>
          {/*<Link>+添加</Link>*/}
          <DictionarySelect
            info={info}
            defaultValue={defaultDependsOnList}
            selectChange={(value) => setDependsOnList(value)}
          />
        </Col>
      </Row>

      <Row>
        <Col span={4} offset={2} className={[styles.item, styles.col]}>
          应用于
        </Col>
        <Col span={16} className={styles.item}>
          {/*<Link>+添加</Link>*/}
          <DictionarySelect
            info={info}
            defaultValue={defaultApplyToList}
            selectChange={(value) => setApplyToList(value)}
          />
        </Col>
      </Row>

      <Row>
        <Col span={4} offset={2} className={[styles.item, styles.col]}>
          引用界面
        </Col>
        <Col span={16} className={styles.item}>
          <DictionarySelect
            info={info}
            defaultValue={defaultRefPageList}
            selectChange={(value) => setRefPageList(value)}
          />
        </Col>
      </Row>

      <Row>
        <Col span={2} offset={10}>
          <Button type={'primary'} onClick={save}>
            保存
          </Button>
        </Col>
      </Row>
    </div>
  );
};

export default AboutLesson;
